﻿using System.Windows;
using System.Windows.Input;
using DesktopToyWpf.Services;

namespace DesktopToyWpf.Views;

/// <summary>
/// Interaction logic for TitleBar.xaml
/// </summary>
public partial class TitleBar
{
    public TitleBar()
    {
        InitializeComponent();
    }

    private Window? ParentWindow;

    private void TitleBar_OnLoaded(object sender, RoutedEventArgs e)
    {
        ParentWindow = Window.GetWindow(this);
        if (ParentWindow == null) return;
        ParentWindow.Activated += Window_OnActivated;
        ParentWindow.Deactivated += Window_OnDeactivated;
        AutoRun.IsChecked = StartupManager.IsStartupEnabled();
    }

    private void Close_MouseDown(object sender, MouseButtonEventArgs e) => ParentWindow?.Close();

    private void Min_OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (ParentWindow != null) 
            ParentWindow.WindowState = WindowState.Minimized;
    }

    private void Window_OnActivated(object? sender, EventArgs e) => UpdateVisible();

    private void Window_OnDeactivated(object? sender, EventArgs e) => UpdateVisible();

    private void UpdateVisible()
    {
        if (ParentWindow == null) return;

        if (ButtonPanel.IsMouseOver || ParentWindow.IsActive)
        {
            Visibility = Visibility.Visible;
        }
        else
        {
            Visibility = Visibility.Hidden;
        }
    }

    private void AutoRun_OnClick(object sender, RoutedEventArgs e)
    {
        StartupManager.SetStartup(AutoRun.IsChecked == true);
    }
}